#!/usr/bin/python
# -*- coding: utf-8 -*-

from ini import *
from utils import *

def init(bot):
	bot.addHook("recieve", hook_room, 'rooms')
	bot.addCommand("makeroom", cmd_makeroom)
	bot.addCommand("roominvite", cmd_roominvite)
	bot.addCommand("roomkick", cmd_roomkick)
	bot.addCommand("joinroom", cmd_joinroom)
	bot.addCommand("leaveroom", cmd_leaveroom)
	
def unload(bot):
	bot.removeHook('hook_room')
	bot.removeCommand(['makeroom', 'roominvite', 'roomkick', 'joinroom', 'leaveroom'])

def hook_room(bot, args):
	return getroom(args[0])
	
def cmd_makeroom(bot, user, args):
	"""Make a sub-room.
Usage: )makeroom <name> [[password]] <users separeated by spaces>
Note: make sure the password is enclosed in square brackets."""
	
	user = getjid(user)
	
	if ' ' in args:
		name, users = args.split(' ', 1)
	else:
		name, users = args, getjid(user)
	name = name.capitalize()
	if not roomexists(name):
		password = ""
		#This will be a list of users who are in other rooms.
		left_out = []
		#Turn the space spareated string into a list.
		users = users.split(' ')
		
		setmaster(user, name)
		adduser(user, user, name)
		
		#The password will be stuck along with that list, so find it.
		if users[0].startswith("[") and users[0].endswith("]"):
			setpassword(user, users.pop(0)[1:-1])
			
		for u in users:
			if not adduser(user, u, name, new = True) and u != user:
				left_out.append(u)
		if left_out:
			bot.sys(user, "Thses users are in other rooms and have not been transferred:\n%s" % "\n".join(left_out))
		bot.sys(user, "You are now the master of the room: %s" % name)
				
	else:
		bot.error(user, "A room named %s already exists." % name)
		
def cmd_roominvite(bot, user, args):
	"""Invite a user into the room.
Usage: )roominvite <user>"""
	pass
		
def cmd_roomkick(bot, user, args):
	"""Kick a user from a room.
Usage: )roomkick <user> [room]
Note: [room] only applys to mods or admins."""

	user = getjid(user)
	
	if ' ' in args:
		target, room = args.split(' ', 1)
	else:
		target, room = args, ""
	
	if isadmin(user) or ismod(user):
		if not room:
			room = getroom(user)
		if inroom(target, room):
			deluser(user, target, master_room)
			bot.sys(user, "%s has been removed from your room." % getdisplayname(target))
			bot.sys(target, "<%s> has removed you from their room." % getdisplayname(user))
		else:
			bot.sys(user, "%s is not in the room." % getdisplayname(target))

	elif ismaster(user):
		master_room = ismaster(user)
		if inroom(target, master_room):
			deluser(user, target, master_room)
			bot.sys(user, "%s has been removed from your room." % getdisplayname(target))
			bot.sys(target, "<%s> has removed you from their room." % getdisplayname(user))
		else:
			bot.sys(user, "%s is not in your room." % getdisplayname(target))
		
def cmd_joinroom(bot, user, args):
	"""Join an existing room.
Usage: )joinroom <name> [password]"""

	user = getjid(user)
	
	if ' ' in args:
		name, password = args.split(' ', 1)
	else:
		name, password = args, ""
	name = name.capitalize()
	
	if roomexists(name):
		if room_passwords[name]:
			if room_passwords[name] == password:
				adduser(user, user, name)
				toroom(bot, user, "<%s> has joined the room." % getdisplayname(user))
			else:
				bot.sys(user, "The password you've submited doesn't match the room's.")
		else:
			adduser(user, user, name)
			toroom(bot, user, "<%s> has joined the room." % getdisplayname(user))
	else:
		bot.error(user, "That room doesn't exist, if you'd like to make a new room use )makeroom.")
		
def cmd_leaveroom(bot, user, args):
	"""Leave the room you're in.
Usage: )leaveroom [room]
Note: Only Admins have a choice on which room to leave."""

	user = getjid(user)

	if getroom(user):
		if ismaster(user):
			master_room = ismaster(user)
			toroom(bot, user, "<%s> has disbanded the room." % getdisplayname(user))
			for u in rooms[master_room]:
				print u
				deluser(user, u, master_room)
				bot.sys(u, "You have been removed from the room: %s" % master_room)
			del room_masters[master_room]
		else:
			deluser(user, user, getroom(user))
			bot.sys(user, "You have left the room: %s" % master_room)
			toroom(bot, user, "<%s> has left the room." % getdisplayname(user))

	else:
		bot.sys(user, "A wise man once said:\n'In order to leave a room, you must be in a room.'")
	savedatabase()
			
def toroom(bot, user, msg):
	user = getjid(user)
	room = getroom(user)
	bot.sendtoroom(msg, room, butnot=[unicode(getjid(user))], name=unicode(getdisplayname(user)))
		
def setpassword(user, password):
	user = getjid(user)
	master_room = ismaster(user)
	if master_room or isadmin(user) or ismod(user):
		if master_room:
			room_password[name] = password
		else:
			room_password[getroom(user)] = password
		return 1
	savedatabase()
	
def setmaster(user, room):
	room = room.capitalize()
	room_masters[room] = getjid(user)
	savedatabase()
			
def adduser(user, target, room, new = False):
	user = getjid(user)
	room = room.capitalize()
	if not getroom(user):
		if roomexists(room):
			rooms[room].append(target)
		else:
			rooms[room] = [target]
	else:
		if target == user or isadmin(user) or ismod(user):
			if new:
				return 0
			moveuser(user, target, room)
		else:
			return 0
	savedatabase()
	return 1
		
def deluser(user, target, room):
	user, target = getjid(user), getjid(target)
	room = room.capitalize()
	if inroom(target, room):
		rooms[room].remove(target)
	if rooms[room] == []:
		del rooms[room]
	savedatabase()
	
def moveuser(user, target, new_room):
	user, target = getjid(user), getjid(target)
	room = room.capitalize()
	for room in rooms.keys():
		if target in room:
			break
	else:
		room = "This room is impossible."
	deluser(user, target, room)
	adduser(user, target, new_room)
	return

